# -*- coding: utf-8 -*-
import sys

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json, execjs
from common.helper import Helper


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "瑞华宫主驾到保障计划"
        self.filename = "commonJS"

    # 生产产品数据
    def genProductInfo(self):
        plan = {
            # 年龄段
            "year": [str(i) for i in range(15, 51)],
            # 性别
            "gender": ["M"],
            # 保障期限
            "expire": ["终身"],
            # 保额
            "money": ["300000", "400000", "500000"],
            # 交费类型
            "payType": ["一次交清"]
        }
        for v in product(plan["year"], plan["gender"], plan["expire"], plan["money"], plan["payType"]):
            self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(
                v[0], v[1], v[2], v[3], v[4]
            ))
            self.mysql._conn.commit()
            print(domain[self.name]["insert_sql"].format(
                v[0], v[1], v[2], v[3], v[4]
            ))

    # 获取请求参数
    def RequestJson(self, dt=None):

        data = {
            "transfer": "GTO2OINTERFACE2017#@!%88",
            "payload": '{"base":{"NAmt":"' + dt[
                "money"] + '","CInsuYear":"106","CFinTyp":"0","NPayTime":"1","CArea":"310000","CProdNo":"990006","CInsuYearFlag":"A"},"applicant":{},"insured":{"TBirthday":"' + str(
                2020 - int(dt[
                               "year"])) + '-01-01","CSex":"f","CCusLvl":"1"},"cvrgList":[{"CCvrgNo":"301023","CCustCvrgNme":"瑞华宫颈恶性肿瘤特定疾病保险","NAmt":"' +
                       dt[
                           "money"] + '","CProdNo":"300023","CNmeCn":"瑞华宫颈恶性肿瘤特定疾病保险","NDductAmt":""}],"prodList":[{"CProdNo":"300023","CProdName":"瑞华宫颈恶性肿瘤特定疾病保险","CFinTyp":"0","NPayTime":"1","CInsuYear":"106","CInsuYearFlag":"A","NHsttPrd":15,"NDssWtPrd":180,"CRdrProd":"0","NGrntExtInsr":-2,"CAutoPadding":"0"}]}'

        }


        packJS = open('./' + self.filename + '/packageList.js', mode='r', encoding="utf-8").read()

        cxt = execjs.compile(packJS)

        # 获取packageList参数值
        packageList = cxt.call("genPackageList", data["payload"])

        form_data = '{"packageList":{"packages":{"header":{"requestType":"RHCALCULATION","comId":"GTO2O20170118","from":"iwechat","sendTime":"' + \
                    packageList["packageList"]["packages"]["header"][
                        "sendTime"] + '","orderSerial":"orderId","comSerial":"comSerial"},"request":"' + \
                    packageList["packageList"]["packages"]["request"] + '"}}}'

        signJS = open('./' + self.filename + '/sign.js', mode='r', encoding="utf-8").read()

        cxt = execjs.compile(signJS)

        # 获取加密签名
        sign = cxt.call("hex_hmac_md5", data["transfer"], packageList)

        r = requests.post(url=domain[self.name]["url"] + "sign=" + sign + "&com_id=GTO2O20170118",
                          headers=domain[self.name]["header"], data=form_data)

        if r.status_code == 200 and "response" in r.text:
            data = (r.json()["packageList"]["packages"]["response"])

            res = self.responseDecode(data)

            result = json.loads(res['responsePayload']["data"])

            price = Helper.decimalParse(result["calPremium"]["cvrgList"][0]["NPrm"])


            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            self.mysql.updatePrice( data )
        else:
            data = {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            self.mysql.updateTask( data )
            print("\n/*产品价格更新失败:%d*/"%dt["id"])
    # # 解码
    def responseDecode(self, data):
        JSdecode = open('./' + self.filename + '/decode.js', mode='r', encoding="utf-8").read()

        cxt = execjs.compile(JSdecode)

        response = cxt.call("decrypt", "", data)

        return response

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.RequestJson(dt)
